/**
 * 创建 Vue 路由实例，用于管理前端路由跳转和页面渲染。
 * 
 * 该文件定义了整个应用的路由结构，包括登录页、用户中心（家长/教师）、学生端、学校端和平台端等模块。
 * 同时预留了基于角色的路由守卫逻辑（当前被注释），可用于权限控制。
 * 
 * 使用方式：
 *   import router from './router'
 *   app.use(router)
 * 
 * @returns {Router} 返回创建好的 Vue Router 实例
 */

import {
    createRouter,
    createWebHistory
} from 'vue-router'
import {
    useLoginStore
} from '../stores/index.js'

/**
 * 定义所有路由配置
 * 
 * 路由结构说明：
 * - 根路径 '/' 重定向到登录页的学生登录子路由
 * - 登录页包含多个子路由：学生、用户（家长/教师）、学校、平台登录
 * - 用户中心分为家长和教师两个主要角色，分别有各自的子页面
 * - 学生端、学校端、平台端各自拥有独立的布局和子页面
 */
const routeHistory = []

const routes = [{
        path: '/',
        redirect: to => ({
            path: '/login/studentsLogin'
        }),
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('../views/login/login_layout.vue'),
        redirect: to => ({
            path: '/login/studentsLogin'
        }),
        children: [{
                path: 'studentsLogin',
                name: 'StudentLogin',
                component: () => import('../views/login/students_login.vue')
            },
            {
                path: 'usersLogin',
                name: 'UserLogin',
                component: () => import('../views/login/users_login.vue')
            },
            {
                path: 'schoolLogin',
                name: 'SchoolLogin',
                component: () => import('../views/login/school_login.vue')
            },
            {
                path: 'platformLogin',
                name: 'PlatformLogin',
                component: () => import('../views/login/platform_login.vue')
            }
        ]
    },
    {
        path: '/user',
        name: 'UserLayout',
        component: () => import('../views/user/layout/layout.vue'),
        redirect: to => ({
            path: '/user/parent/home'
        }),
        children: [

            // 家长路由
            {
                path: 'parent',
                name: 'ParentLayout',
                component: () => import('../views/user/parent/layout/layout.vue'),
                redirect: to => ({
                    path: '/user/parent/home'
                }),
                children: [{
                        path: 'home',
                        name: 'ParentHome',
                        component: () => import('../views/user/parent/home/home.vue'),
                    },
                    {
                        path: 'mychild',
                        name: 'ParentMychild',
                        component: () => import('../views/user/parent/mychild/mychild.vue')
                    },
                    {
                        path: 'course',
                        name: 'ParentCourse',
                        component: () => import('../views/user/common/course/course.vue'),
                    },
                    {
                        path: 'forum',
                        name: 'ParentForum',
                        component: () => import('../views/user/common/forum/forum.vue'),
                    }, {
                        path: 'info',
                        name: 'ParentInfo',
                        component: () => import('../views/user/common/info/info.vue')
                    }, {
                        path: 'groupChat/:classId',
                        name: 'GroupChat',
                        component: () => import('../views/user/parent/groupChat/groupChat.vue'),
                    }
                ]
            },
            // 教师路由
            {
                path: 'teacher',
                name: 'TeacherLayout',
                component: () => import('../views/user/teacher/layout/layout.vue'),
                redirect: to => ({
                    path: '/user/teacher/home'
                }),
                children: [{
                        path: 'home',
                        name: 'TeacherHome',
                        component: () => import('../views/user/teacher/home/home.vue'),
                    },
                    {
                        path: 'subject',
                        name: 'TeacherSubject',
                        component: () => import('../views/user/teacher/subject/subject.vue'),
                    },
                    {
                        path: 'course',
                        name: 'TeacherCourse',
                        component: () => import('../views/user/common/course/course.vue'),
                    },
                    {
                        path: 'forum',
                        name: 'TeacherForum',
                        component: () => import('../views/user/common/forum/forum.vue'),
                    }, {
                        path: 'info',
                        name: 'TeacherInfo',
                        component: () => import('../views/user/common/info/info.vue')
                    },
                    // 在教师路由部分添加
                    {
                      path: 'groupChat/:classId',
                      name: 'TeacherGroupChat',
                      component: () => import('../views/user/teacher/groupChat/groupChat.vue')
                    }
                ]
            }
        ]
    }, {
        path: '/student',
        name: 'StudentLayout',
        component: () => import('../views/student/layout/layout.vue'),
        redirect: to => ({
            path: '/student/home'
        }),
        children: [{
                path: 'home',
                name: 'StudentHome',
                component: () => import('../views/student/home/home.vue')
            }, {
                path: 'info',
                name: 'StudentInfo',
                component: () => import('../views/student/info/info.vue'),
                meta: {
                    requiresAuth: true,
                    role: 'student'
                } // 需登录且为学生角色
            }, {
                path: 'course',
                name: 'StudentCourse',
                component: () => import('../views/student/course/course.vue')
            },  {
                path: 'homework',
                name: 'StudentHomework',
                component: () => import('../views/student/homework/homework.vue'),
                meta: {
                    requiresAuth: true,
                    role: 'student'
                }
            }
        ]
    }, {
        path: '/school',
        name: 'SchoolLayout',
        component: () => import('../views/school/layout/layout.vue'),
        redirect: to => ({
            path: '/school/home'
        }),
        children: [{
            path: 'home',
            name: 'SchoolHome',
            component: () => import('../views/school/home/home.vue')
        }, {
            path: 'teacher',
            name: 'SchoolTeacher',
            component: () => import('../views/school/teacher/teacher.vue')
        }, {
            path: 'student',
            name: 'SchoolStudent',
            component: () => import('../views/school/student/student.vue')
        }, {
            path: 'course',
            name: 'SchoolCourse',
            component: () => import('../views/school/course/course.vue')
        }, {
            path: 'info',
            name: 'SchoolInfo',
            component: () => import('../views/school/info/info.vue')
        }]
    }, {
        path: '/platform',
        name: 'PlatformLayout',
        component: () => import('../views/platform/layout/layout.vue'),
        redirect: to => ({
            path: '/platform/home'
        }),
        children: [{
            path: 'home',
            name: 'PlatformHome',
            component: () => import('../views/platform/home/home.vue')
        }, {
            path: 'school',
            name: 'PlatformSchool',
            component: () => import('../views/platform/school/school.vue')
        }, {
            path: 'accountAdmin',
            name: 'PlatformAccountAdmin',
            component: () => import('../views/platform/accountAdmin/accountAdmin.vue')
        }, {
            path: 'course',
            name: 'PlatformCourse',
            component: () => import('../views/platform/course/course.vue')
        }]
    }
]

/**
 * 创建并导出 Vue Router 实例
 * 
 * 使用 HTML5 History 模式进行路由管理
 */
const router = createRouter({
    history: createWebHistory(),
    routes
})

// 路由前置守卫
router.beforeEach((to, from) => {
    const loginStore = useLoginStore()
    const isAuthenticated = loginStore.token
    const userRole = loginStore.user.role

    // 定义免认证白名单
    const allowList = [
        'StudentLogin',
        'UserLogin',
        'SchoolLogin',
        'PlatformLogin',
    ]

    // 情况1：访问的是白名单路由
    if (allowList.includes(to.name)) {
        // 如果已登录，重定向到首页
        if (isAuthenticated) {
            return {
                name: redirectToHomePage(userRole)
            }
        }
        // 未登录则允许访问
        return true
    }

    // 情况2：访问的是需要认证的路由
    if (!allowList.includes(to.name)) {
        // 未登录用户尝试访问受保护路由，重定向到登录页
        if (!isAuthenticated) {
            return {
                name: 'StudentLogin'
            }
        }
        return true
    }

    // 所有检查通过，允许导航
    return true
})

// 根据角色重定向到对应首页
function redirectToHomePage(role) {
    const homeRoutes = {
        'student': 'StudentHome',
        'user': 'ParentHome',
        // 'teacher': 'TeacherHome',
        'school': 'SchoolHome',
        'platform': 'PlatformHome'
    }
    return homeRoutes[role]
}

// 全局后置守卫：记录每次路由跳转
router.afterEach((to, from, failure) => {
  if (!failure) { // 跳转成功时才记录
    routeHistory.push({
      time: new Date().toLocaleString(), // 跳转时间
      from: {
        path: from.path,
        name: from.name,
        params: from.params
      },
      to: {
        path: to.path,
        name: to.name,
        params: to.params
      }
    })
    
    // 限制历史记录最大条数（避免内存占用过多）
    if (routeHistory.length > 100) {
      routeHistory.shift() // 删除最早的记录
    }
    
    // 控制台打印记录（方便调试）
    console.log('路由跳转记录:', routeHistory)
  }
})

// 暴露历史记录（供组件中使用）
export { routeHistory }

export default router